<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>查找数组中最小和第二小的元素</title>
    <script>
         function find2smallest(arr)
    {
        let first =Number.MAX_VALUE;
        let second = Number.MAX_VALUE;
        let i;
        if(arr.length<2)
        {
            console.log("请确保数组中至少包括两个数值");
            return;
        }
        for(i=0;i<arr.length;i++)
        {
            //若arr[i]小于最小first，则first进行数据更新，同时原first值作为second的参考值
            if(arr[i]<first)
            {
                second = first;
                first = arr[i];
            }
            //arr[i]！=first,排除重复数值
            //上面的if循环保证first最小,必然满足arr[i]>=first,如此时arr[i]<second,则可能为第二小数
           else if(arr[i]<second && arr[i]!=first)
           {
               second =arr[i];
           }
        }
         if(second === Number.MAX_VALUE)
        {
               console.log("没有第二小的数值");
        } 
        else
        {
               console.log("first:"+first);
               console.log("second:"+second);
        }
    }
    //let arr = [ 2,3,12,9, 13, 1, 10, 34, 1 ]
    let arr =[-2,-1,5,2,10,8,4];
    find2smallest(arr);


        // var arr = [3, 13, 2, 73, 52, 6, 92];
        // var tmp;
        // for (var i = 0; i < arr.length; i++) {
        //     for (var j = i + 1; j < arr.length; j++) {
        //         if (arr[i] > arr[j]) {
        //             tmp = arr[j];
        //             arr[j] = arr[i];
        //             arr[i] = tmp;
        //         }
        //     }
        // }
        // // console.log(arr);
        // console.log("最小为" + arr[0] + "第二小为" + arr[1])
    </script>
</head>

<body>

</body>

</html>